#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <vector>

// 多线程
const int num = 10;
std::vector<pthread_t> tids;


void* routine(void* args)
{
    sleep(1);
    std::string name = static_cast<const char*>(args);
    delete (char*)args;
    int cnt = 5;
    while(cnt--)
    {
        std::cout << "这是一个新线程, name : " << name << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    // 创建新线程
    for(int i = 0; i < num; i++)
    {
        char* id = new char[64];
        snprintf(id, 64, "thread-%d", i);
        pthread_t tid;
        int n = pthread_create(&tid, nullptr, routine, id);
        if(n == 0) 
            tids.push_back(tid);
        else 
            continue;
    }

    // 等待新线程 一个一个等待
    for(int i = 0; i < tids.size(); i++)
    {
        int n = pthread_join(tids[i], nullptr);
        if(n == 0) 
            std::cout << "线程等待成功" << std::endl;
    }
    return 0;
}